<?php
/**
 * 充值API
 * Created by PhpStorm.
 * User: poptser
 * Email: poptser@foxmail.com
 * Date: 2016/8/16
 * Time: 10:54
 */

namespace YMApi\Controller;
use Think\Controller;
use Com\Alipay\AlipaySubmit;
use Com\Alipay\AlipayNotify;

class RechargeController extends AppController
{
    public $alipay_config=array();
    public $weinxin_key = "";

    public function _initialize($apptoken, $apptime, $check_uid = false)
    {
        parent::_initialize($apptoken, $apptime, true); // TODO: Change the autogenerated stub

        $this->alipay_config = array(
            'seller_id' => '2088811720960505',                                          //合作身份者ID
            'partner' => '2088811720960505',                                            //合作身份者ID
            'key' => 'cgfk1p3u0dngsghykks56rezaxqsbkpu',                                //KEY
            'transport' => 'http',
            'payment_type' => '1',
            'service' => 'alipay.wap.create.direct.pay.by.user',
            'notify_url' => $_SERVER['HTTP_HOST'].U("Alipaynotify/alipay_notifypay"),              //异步判断支付结果
            //'return_url' => "http://localhost:82/index.php/Recharge/my_recharge.html",  //同步判断地址
            'sign_type' => strtoupper('MD5'),
            'input_charset' => strtolower('utf-8'),
        );

    }


    /**
     *充值操作
     */
    public function my_recharge(){
        
        
        $uid=$this->uid;
        
        //判断用户是否绑定手机号码
        
        $user_phone = D("Users")->get_user_phone($uid);
        if(!$user_phone){
            returnApiError("未绑定手机号，请先绑定");
        }
        $pay_type = I("post.pay_type");     //所选择的支付方式
        $amount = I("post.amount");     //所选择的支付金额
        $trade_type = I('app_type');		//支付类型。app为app支付
        //创建
        $amount=sprintf('%.2f',$amount); 
        $surplus['user_id'] = $this->uid;
        $surplus['amount'] = $amount;
        $surplus['process_type'] = 0;
        $surplus['admin_note'] = 0;
        $surplus['user_note'] = 0;
        $surplus['payment'] = '支付宝';
        $subject['is_hd'] = $this->is_hd;
        
        empty($subject['is_hd'])?$subject['is_hd']='-1':$subject['is_hd'];


        $out_trade_no = D("Payment")->add_recharge_log($surplus,$amount);   //订单号
        
        $subject = "充值，金额:".$amount;//订单名称，必填
        $total_fee = $amount;//付款金额，必填
        $show_url = "http://w.shidexian.com/index.php";//收银台页面上，商品展示的超链接，必填
        $body = "食得鲜-账户充值"; //商品描述，可空


        if($pay_type==2&&$amount>0){
            
            //判断是否符合充60送100元活动
            /* $users = M("users")->field("password,paypwd",true)->where(array("user_id"=>$uid,"user_rank"=>array("in","0,1")))->find();
            if($users&&in_array(floatval($amount),array(60,120,180,240,300,360,420,480,540,600))&&gmtime()<strtotime("2016-11-30 23:59:59")){
                $my_60_activity = M("user_account")->field("sum(amount) as sur_amount")->where(array("is_pay"=>1,'admin_note'=>array('neq','混合支付'),"user_id"=>$uid,"amount"=>array("in","60,120,180,240,300,360,420,480,540,600"),"paid_time"=>array('between',strtotime("2016-11-1").",".strtotime("2016-11-30 23:59:59"))))->select();
                $my_60_surplus_num=(600-($my_60_activity[0]['sur_amount']+$amount))/60;
                if($my_60_surplus_num<0){
                    returnApiError('您的充60得100充值次数超出10次，不允许再充值！');
                }
            } */
            
            D("Payment")->check_Recharge_amount($uid,$amount);
            
            
            $surplus['payment'] = "支付宝";

            $notify_url = "http://".$_SERVER['HTTP_HOST']."/pay_notice.php";              //异步判断支付结果
            $return_url = "http://w.shidexian.com/index.php#index4";           //同步判断地址
            if($trade_type=="app"){
                
            	$alipay_from['payinfo'] = D("Payment")->app_alipay($out_trade_no, $subject, $total_fee, $show_url, $body,$notify_url,$return_url);
            	returnApiSuccess($alipay_from,'Transfer from the success of Alipay');
            }else{
                
            	$alipay_from['from'] = D("Payment")->alipay($out_trade_no,$subject,$total_fee,$show_url,$body,$notify_url,$return_url);
            	returnApiSuccess($alipay_from,'Transfer from the success of Alipay,Please show this from to page');
            }
        }else{
            returnApiError('pay_type is not in the library or price is positive number');
        }

    }
    
    /*
     * 获取充值类型列表
     */
    
    public function recharge_type_list(){
    	$version = I('post.version');
		$uid = I('post.uid');
    	if(!IS_POST){
    		returnApiError('error request');
    	}
		if(empty($uid)){
    	    returnApiError('uid is null');
    	}
    	
    	
    	
    	
    	if(empty($version)){
    		$type_list = array(
    				array('type'=>'1','price'=>'1000','give_type'=>'1','descrition'=>'送VIP会员','give_price'=>0,'expire'=>'','pic'=>''),
    				array('type'=>'2','price'=>'2980','give_type'=>'1','descrition'=>'送魔镜机器人一年使用权（价值4万）','give_price'=>0,'expire'=>'','pic'=>''),
    				array('type'=>'3','price'=>'2980','give_type'=>'1','descrition'=>'送神灯机器人一年使用权（价值4万）','give_price'=>0,'expire'=>'','pic'=>''),
    				array('type'=>'4','price'=>'9800','give_type'=>'1','descrition'=>'送小宝机器人一年使用权（价值8万）','give_price' => 0,'expire' => '','pic' => '' ) 
			);
		} else {
		    $type_list=D("Payment")->check_Recharge_time($uid);
		    
    		$now = gmtime();
			foreach ($type_list as $key=>$val){
				if($val['is_activity']==1){
					if($now>$val['activity_limit_notice_time'] && $now<$val['expire_time']){
						$type_list[$key]['expiration_notice']="即将过期";
					}
				}

				if (!empty($val['expire_time'])) {
					$type_list[$key]['expire'] = $val['expire_time'];
				}
			}
    	}
    	
    	$res['list'] = $type_list;
        $res['note'] = "仅限广州配送区域内及到店自提用户充值";
        $explain=M("recharge_setting_explain")->order("num asc")->select();
        $i=1;
        foreach($explain as $item){
            $res['note2'][] = $i."、".$item['content'];
            $i++;
        }
        
        

    	returnApiSuccess($res);
    }
}